package hu.gbalage.httpserver;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class HttpSingleFile implements HttpHandler{

	//private final File file;
	
	private byte[] b;
	
	private void processFile(File file) throws IOException{
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
		int length = bis.available();
		byte[] b = new byte[length];
		bis.read(b);
		bis.close();
	}
	
	public HttpSingleFile(InputStream is){
		try{
			//BufferedInputStream bis = new BufferedInputStream(is);
			int length = is.available();
			byte[] b = new byte[length];
			is.read(b);
			is.close();
			System.out.println("File size: "+b.length+" bytes.");
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public HttpSingleFile(String fn){
		super();
		File file = new File(fn);
		try {
			processFile(file);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public HttpSingleFile(URI uri){
		super();
		File file = new File(uri);
		try {
			processFile(file);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public HttpSingleFile(URL url){
		super();
		File file;
		try {
			file = new File(url.toURI());
		} catch (URISyntaxException e) {
			file = null;
			e.printStackTrace();
		}
		try {
			processFile(file);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void handle(HttpExchange arg0) throws IOException{
		System.out.println("Sending "+b.length+" bytes..");
		arg0.getRequestHeaders().add("Content-Type", "text/css");
		arg0.sendResponseHeaders(200, b.length);
		
		BufferedOutputStream out = new BufferedOutputStream(arg0.getResponseBody());
		out.write(b);
		out.close();
		System.out.println("Done.");
	}
}
